#!/bin/bash
# Solum script for building custom languagepacks

SCRIPT_START_TIME=$(date +'%s')
TASKNAME=languagepack
ASSEMBLY_ID=${ASSEMBLY_ID:-null}
REUSE_IMAGES_IF_REPO_UNCHANGED=${REUSE_IMAGES_IF_REPO_UNCHANGED:="0"}
GIT_PRIVATE_KEY=${REPO_DEPLOY_KEYS:-''}
IMAGE_STORAGE=${IMAGE_STORAGE:-null}
DELETE_LOCAL_CACHE=${DELETE_LOCAL_CACHE:-null}
LP_ACCESS=${ACCESS:-null}

OS_AUTH_TOKEN=${OS_AUTH_TOKEN:-null}
OS_REGION_NAME=${OS_REGION_NAME:-null}
OS_STORAGE_URL=${OS_STORAGE_URL:-null}

TEMP_URL_SECRET=${TEMP_URL_SECRET:-null}
TEMP_URL_PROTOCOL=${TEMP_URL_PROTOCOL:-null}
TEMP_URL_TTL=${TEMP_URL_TTL:-null}

OPR_LP_DOWNLOAD_STRATEGY=${OPR_LP_DOWNLOAD_STRATEGY:-null}

# TLOG, PRUN, etc. defined in common/utils
HERE=$(dirname $0)
source $HERE/../../common/utils

LOG_FILE=$(GET_LOGFILE)

# Get the image uuid of the image named $1
function app_glance_id () {
  glance --os-image-api-version 2 --os-auth-token $OS_AUTH_TOKEN image-list --sort-key updated_at --sort-dir asc | grep $1 | grep -v "+--" | tail -1 | cut -d'|' -f2
}

function cleanup_on_exit () {
  if [[ $DELETE_LOCAL_CACHE == "true" ]]; then
    # Not Deleting languagepack image because we found it conflicts with docker load in
    # performance tests, which might be due to a concurrency bug in docker load and rmi.
    #if [[ -n $LP_IMG_TAG ]]; then
    #  sudo docker rmi -f $LP_IMG_TAG
    #fi

    # Delete the cloned git repo
    if [[ -n $TMP_LP_DIR ]]; then
      rm -rf $TMP_LP_DIR
    fi

    # Delete temp output file
    if [[ -n $LP_FILE ]] && [[ -e $LP_FILE ]]; then
      rm -f $LP_FILE
    fi
  fi
}

TLOG ===== Starting Language Pack Build Script $0 $*

# Make sure tenant auth credentials were passed in.
if [[ -z $OS_AUTH_TOKEN ]]; then
  TLOG openstack credentials not passed via ENV. && exit 1
fi

# Check command line arguments
if [[ $# -lt 3 ]]; then
  TLOG Usage: $0 git_url lpname project_id && exit 1
fi

PRUN silent sudo docker ps
[[ $? != 0 ]] && TLOG cannot talk to docker. && exit 1

GIT=$1
shift
LPNAME=$1
shift
TENANT=$1

TS=$(date +"%Y%m%dt%H%M%S%N")
GIT_CHECKSUM=$(echo $GIT | md5sum | awk '{print $1;}')
TMP_LP_DIR="/tmp/lps/$TENANT/$ASSEMBLY_ID"
mkdir -p $TMP_LP_DIR

trap cleanup_on_exit EXIT

TLOG ===== Cloning repo
git_clone_with_retry $GIT $TMP_LP_DIR/build
[[ $? != 0 ]] && TLOG Git clone failed. Check repo $GIT && exit 1

if [[ -d "$TMP_LP_DIR/build" ]]; then
  cd $TMP_LP_DIR/build
  COMMIT_ID=$(git log -1 --pretty=%H)
  LP_IMG_TAG="$TENANT-$LPNAME-$TS-$COMMIT_ID"
  STORAGE_OBJ_NAME="$LPNAME-$TS-$COMMIT_ID"

  echo ".git" > .dockerignore

  TLOG Building LP
  if [[ $IMAGE_STORAGE == "glance" ]]; then
    PRUN silent glance --os-image-api-version 2 --os-auth-token $OS_AUTH_TOKEN image-list
    if [[ $? != 0 ]]; then
      TLOG Cannot talk to Glance. Check your OpenStack credentials. && exit 1
    fi

    docker_build_with_retry $LP_IMG_TAG .
    [[ $? != 0 ]] && TLOG Docker build failed. && exit 1
    TLOG ===== finished docker build

    sudo docker save "$LP_IMG_TAG" | glance --os-image-api-version 2 --os-auth-token $OS_AUTH_TOKEN image-create --container-format=docker --disk-format=raw --name "$STORAGE_OBJ_NAME"
    if [[ $? != 0 ]]; then
      TLOG Failed to upload languagepack to glance. && exit 1
    fi
    TLOG ===== finished uploading LP to $IMAGE_STORAGE

    image_id="$(app_glance_id $STORAGE_OBJ_NAME)"
    # Tag the glance image as a solum language pack
    TLOG ===== tagging glance image $image_id
    glance --os-auth-token $OS_AUTH_TOKEN --os-image-api-version 2 image-tag-update $image_id 'solum::lp'
  elif [[ $IMAGE_STORAGE == "swift" ]]; then
    docker_build_with_retry $LP_IMG_TAG .
    [[ $? != 0 ]] && TLOG Docker build failed. && exit 1
    TLOG ===== finished docker build

    LP_FILE="$TMP_LP_DIR/$STORAGE_OBJ_NAME"
    docker_save_with_retry $LP_FILE $LP_IMG_TAG
    [[ $? != 0 ]] && TLOG Docker save failed. && exit 1

    python $HERE/swift-handler.py $OS_REGION_NAME $OS_AUTH_TOKEN $OS_STORAGE_URL upload solum_lp $STORAGE_OBJ_NAME $LP_FILE \
    > >(while read ALINE; do TLOG $ALINE; done)
    if [[ $? != 0 ]]; then
      TLOG Failed to upload languagepack to swift. && exit 1
    fi

    if [[ $LP_ACCESS == "custom" ]]; then
      image_id="${STORAGE_OBJ_NAME}"
    elif [[ $LP_ACCESS == "operator" ]]; then
      if [[ $OPR_LP_DOWNLOAD_STRATEGY == "swift-client" ]]; then
        image_id="${STORAGE_OBJ_NAME}"
      elif [[ $OPR_LP_DOWNLOAD_STRATEGY == "wget" ]]; then
        ACCOUNT=$(echo $OS_STORAGE_URL | sed 's/\// /'g | awk '{print $4}')
        TLOG "ACCOUNT=$ACCOUNT"
        STORAGE_HOST=$(echo $OS_STORAGE_URL | sed 's/\// /'g | awk '{print $2}')
        TLOG "STORAGE_HOST=$STORAGE_HOST"

        TLOG "STORAGE_URL:$OS_STORAGE_URL"
        TLOG "REGION:$OS_REGION_NAME"
        TLOG "AUTH_TOKEN:$OS_AUTH_TOKEN"

        curl -i -X POST -H X-Auth-Token:$OS_AUTH_TOKEN -H X-Account-Meta-Temp-URL-Key:$TEMP_URL_SECRET $TEMP_URL_PROTOCOL://$STORAGE_HOST/v1/$ACCOUNT
        TLOG "HERE:$HERE"

        TEMP_URL=$(python $HERE/get-temp-url.py $STORAGE_HOST solum_lp $STORAGE_OBJ_NAME $ACCOUNT $TEMP_URL_SECRET $TEMP_URL_TTL $TEMP_URL_PROTOCOL)
        TLOG "TEMP_URL:$TEMP_URL"

        image_id="${TEMP_URL}"
      fi
    fi

    TLOG ===== finished uploading LP to $IMAGE_STORAGE
  elif [[ $IMAGE_STORAGE == "docker_registry" ]]; then
    DOCKER_REGISTRY=${DOCKER_REGISTRY:-'10.0.2.15:5042'}
    docker_build_with_retry $LP_IMG_TAG .
    [[ $? != 0 ]] && TLOG Docker build failed. && exit 1
    TLOG ===== finished docker build

    APP_NAME="$DOCKER_REGISTRY/$LP_IMG_TAG"
    TLOG "APP_NAME=$APP_NAME"
    PRUN sudo docker tag $LP_IMG_TAG $APP_NAME

    sudo docker push $APP_NAME
    if [[ $? != 0 ]]; then
      TLOG Failed to upload languagepack to docker registry. && exit 1
    fi
    TLOG ===== finished uploading LP to $IMAGE_STORAGE

    # Just to make work/shell easier to process
    image_id="${APP_NAME}"
    sudo docker rmi -f $APP_NAME
  else
    TLOG Unsupported Image storage backend - $IMAGE_STORAGE && exit 1
  fi
fi

TOTAL_TIME=$(elapsed $SCRIPT_START_TIME)
TLOG ===== Total elapsed time: $TOTAL_TIME sec

TLOG image_external_ref=$image_id
TLOG docker_image_name=$LP_IMG_TAG

# Need stdout for solum-worker to parse the image_id
echo image_external_ref=$image_id
echo docker_image_name=$LP_IMG_TAG

exit 0
